from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from ai_utils import hub_utils
from gen_video.templates import template_on_video
from spider import serializers
from spider.models import YtbCommentTaskLog
from spider.utils import download_video
from spider.ytb_comment.comment import csv_to_data


class YtbCommentTaskLogViewSet(ModelViewSet):
    # pip uninstall youtube_dl
    queryset = YtbCommentTaskLog.objects.all()
    serializer_class = serializers.YtbCommentTaskLogCreateSerializer

    def get_serializer_class(self):
        if self.action in ['create','update']:
            return serializers.YtbCommentTaskLogCreateSerializer
        return serializers.YtbCommentTaskLogSerializer

    @action(methods=['GET'],detail=True)
    def show_comments(self,request,*args,**kwargs):
        instance = self.get_object()
        file = instance.file_path.url
        data = csv_to_data(file[1:])
        return Response(data)

    @action(methods=['get'],detail=True)
    def gen_video(self,request,*args,**kwargs):
        # 检测是否已经存在本地视频
        instance = self.get_object()
        if not instance.file_path:
            return Response({'code':-1,'msg':'还没有存在评论数据'})
        if not instance.src_video_path:
            # todo:msg：还没有存在本地视频
            is_success,video_path = download_video(instance.vid)
            if not is_success:
                return Response({'code':-1,'msg':'获取视频失败'})
            instance.src_video_path = video_path
            instance.save()
        video_file = instance.src_video_path
        src_video_url = request.get_host()+'/'+ video_file

        # 获取评论列表
        csv_path = instance.file_path.url
        comment_data = csv_to_data(csv_path[1:])
        # comment_list = [i['textOriginal']+'\n'+i['zh'] for i in comment_data]
        comment_list = [i['zh'] for i in comment_data]
        result_video = template_on_video(comment_list, video_file, "static/material/img/youtube_logo.png",
                          "media/material/music/mzt.mp3",text_font='static/fonts/simsun.ttc')
        instance.final_video_path = result_video
        instance.save()
        result_video_url = request.get_host()+'/'+ result_video
        return Response({'result_video_url':result_video_url,'src_video_url':src_video_url})
